import 'package:flutter/material.dart';
import 'package:wheel_of_fortune/http/wheel_server.dart';
import 'package:wheel_of_fortune/model/rotary_table_model.dart';
import 'package:wheel_of_fortune/utils/utils.dart';

class WheelOfFortuneProvider extends ChangeNotifier {
  RotaryTableModel model;
  double candyBalance = 0;
  bool isCanSpin = true;
  initData() {
    getCandyBalance();
    getRotaryTable();
  }

  getRotaryTable() async {
    try {
      model = await WheelService().getRotaryTableModel();
      bool canSpin = DateTimeHelper.isCanSpin(
        model.currentTime,
        model.startTime,
        model.endTime,
        model.startDate,
        model.endDate,
      );
      if (canSpin && (model.pay || model.candyExchange || model.topUpPresented)) {
        isCanSpin = true;
      } else {
        isCanSpin = false;
      }
    } catch (e) {
      print(e);
      model = RotaryTableModel();
    }
    notifyListeners();
  }

  Future getAward() async {
    try {
      final data =
          await WheelService().getAward(model?.rotaryTableId ?? 'test');
      return data;
    } catch (e) {
      print('e = ${e.message}');
      return e.message;
    }
  }

  Future getCandyBalance() async {
    try {
      final data = await WheelService().getCandyBalance();
      candyBalance = data['balance'];
      notifyListeners();
      return data;
    } catch (e) {
      print('e = $e');
      notifyListeners();
      return e;
    }
  }

  Future candyExchange(id, acount) async {
    try {
      final data = await WheelService()
          .candyExchange(model.rotaryTableId, model.candyExchangeAmount);
      notifyListeners();
      return data;
    } catch (e) {
      print('e = $e');
      notifyListeners();
      return e;
    }
  }

  Future collectPrize(String id,
      {String address,
      int cityMunicipalityId,
      String cityName,
      int provinceId,
      String provinceName}) async {
    try {
      await WheelService().collectPrize(id, address, cityMunicipalityId, cityName, provinceId, provinceName);
      return 'success';
    } catch (e) {
      return e.toJson();
    }
  }
}
